from selenium.webdriver.support.expected_conditions import presence_of_element_located
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium import webdriver
import pyautogui as pi
import xlrd
import time
class User:
    def __init__(self,Account,Name,Amount,FullUrl,ProjectType,Id):
        self.__Account = Account
        self.__Password = "123456"
        self.__Phone="18971592077"
        self.__Name = Name
        self.__Amount = Amount
        self.__FullUrl = FullUrl
        self.__ProjectType = ProjectType
        self.__Id = Id
    def getId(self):
        return self.__Id
    def getAccount(self):
        return  self.__Account
    def getPassword(self):
        return self.__Password
    def getPhone(self):
        return self.__Phone
    def getName(self):
        return self.__Name
    def getAmount(self):
        return self.__Amount
    def getFullUrl(self):
        return self.__FullUrl
    def getProjectType(self):
        return self.__ProjectType
    def getDaili(self):
        begin_str = self.getAccount()[0:2]
        if(begin_str == 'xz'):
            return True
        else:
            return False

def GetSetting():
    filepath = './cp.xls'
    workbook =  xlrd.open_workbook(filepath)
    worksheet1 = workbook.sheet_by_name('sheet1')
    settings = []
    temp1 = ""
    for i in range(6):
        if i < 3 :
            if i ==2:
                temp1 = str(worksheet1.cell_value(1,i))[0:-2]
            else:
                temp1 = str(worksheet1.cell_value(1,i))
            settings.append(temp1) 
        elif i <5:
            temp1 = str(worksheet1.cell_value(1,i))
            settings.append(temp1)
        else:
            temp1 = str(worksheet1.cell_value(2,2)) 
            settings.append(temp1) 
    return settings

def SetUrl(s1):
    begin_url = "http://"
    end_url = '/member/login/executeLogin.htm'
    s =  begin_url + s1 + end_url 
    return s

def GetProjectType(settings):
    if settings[3] == "11" :
        projectType = "CA招标项目"
    elif settings[3]=="12":
        projectType = "CA竞争性谈判项目"
    elif settings[3] == "13":
        projectType = "CA询价采购项目"
    elif settings[3] == "14":
        projectType = "CA竞争性磋商项目"
    elif settings[3] == "15":
        projectType = "CA供应商入围"
    elif settings[3] == "21":
        projectType = "无CA单一来源采购"
    elif settings[3] == "22":
        projectType = "无CA竞价项目"
    elif settings[3] == "23":
        projectType = "无CA谈判采购项目"
    elif settings[3] == "24":
        projectType = "无CA询价采购项目"
    elif settings[3] == "25":
        projectType = "无CA供应商入围"
    elif settings[3] == "26":
        projectType = "无CA议价项目"
    return projectType
def GetFullUrl(settings):
    if settings[2].upper() == 'CUSTOM':
        fullUrl = SetUrl(settings[5])
    elif settings[2].upper() == "LOCAL":
        fullUrl = SetUrl('localhost:6850')
    elif settings[2].upper() == "UAT":
        fullUrl = SetUrl('61.187.51.25:8084')
    elif settings[2].upper() == "DEV":
        fullUrl = SetUrl('61.187.51.25:8800')
    elif settings[2].upper() == "PROD":
        fullUrl = SetUrl("www.holdcg.com")
    else:
        fullUrl = "http://www.baidu.com"
    return fullUrl

def sendKeyElement_id(driver,id1,keys):
    locationLogin=(By.ID,id1)
    try:
        WebDriverWait(driver,20,0,50).until(presence_of_element_located(locationLogin))
    except:
        print("Debug:presence_of_element this element not found by ID:",id1)
    try:
        WebDriverWait(driver,20,0,5).until(EC.visibility_of_element_located(locationLogin))
    except:
        print("Debug:EC this element not found by ID:",id1)
    try:
        driver.find_element(By.ID,id1).send_keys(keys)
    except:
        print("Debug:find_element this element not fond by id :" , id1)
def clickElement_id(driver,id1):
    locationLogin=(By.ID,id1)
    try:
        WebDriverWait(driver,20,0,50).until(presence_of_element_located(locationLogin))
    except:
        print("Debug: this element not found by ID:",id1)
    try:
        WebDriverWait(driver,20,0,5).until(EC.visibility_of_element_located(locationLogin))
    except:
        print("Debug:this element not found by ID:",id1)
    try:
        driver.find_element(By.ID,id1).click()
    except:
        print("Debug:this element not fond by id :" , id1)
def clickElement_link(driver,link1):
    locationLogin=(By.LINK_TEXT,link1)
    try:
        WebDriverWait(driver,20,0,50).until(presence_of_element_located(locationLogin))
    except:
        print("Debug:this element not found by link:-",link1)
    try:
        WebDriverWait(driver,20,0,5).until(EC.visibility_of_element_located(locationLogin))
    except:
        print("Debug:this element not found by xpath:-",link1)
    try:
        driver.find_element(By.LINK_TEXT,link1).click()
    except:
        print("Debug: this element not found by link:-",link1)

def sendKeyElement_link(driver,link1,keys):
    locationLogin=(By.LINK_TEXT,link1)
    try:
        WebDriverWait(driver,20,0,50).until(presence_of_element_located(locationLogin))
    except:
        print("Debug:this element not found by link1:",link1)
    try:
        WebDriverWait(driver,20,0,5).until(EC.visibility_of_element_located(locationLogin))
    except:
        print("Debug:this element not found by link:",link1)
    try:
        driver.find_element(By.LINK_TEXT,link1).send_keys(keys)
    except:
        print("Debug: this element not found by link:",link1)

def clickElement_xpath(driver,xpath1):
    locationLogin=(By.XPATH,xpath1)
    try:
        WebDriverWait(driver,20,0,50).until(presence_of_element_located(locationLogin))
    except:
        print("Debug:this element not found by xpath:",xpath1)
    try:
        WebDriverWait(driver,20,0,5).until(EC.visibility_of_element_located(locationLogin))
    except:
        print("Debug:this element not found by xpath:",xpath1)
    try:
        driver.find_element(By.XPATH,xpath1).click()
    except:
        print("Debug: this element not found by xpath:",xpath1)

def sendKeyElement_xpath(driver,xpath1,keys):
    locationLogin=(By.XPATH,xpath1)
    try:
        WebDriverWait(driver,20,0,50).until(presence_of_element_located(locationLogin))
    except:
        print("Debug:this element not found by xpath:",xpath1)
    try:
        WebDriverWait(driver,20,0,5).until(EC.visibility_of_element_located(locationLogin))
    except:
        print("Debug:this element not found by xpath:",xpath1)
    try:
        driver.find_element(By.XPATH,xpath1).send_keys(keys)
    except:
        print("Debug: this element not found by xpath:",xpath1)

def getTimeStrip():
    #return time.strftime("%Y{}%m{}%d{} %H{}%M{}%S{}",time.localtime()).format('年','月','日','时','分','秒')
    return time.strftime("%Y{}%m{}%d{}-%H{}%M{}",time.localtime()).format('年','月','日','点','分')
def pmlogin(driver, person):
    driver.get(person.getFullUrl())
    locationLogin = (By.LINK_TEXT, '立即登录')
    try:
        WebDriverWait(driver, 20, 0, 5).until(presence_of_element_located(locationLogin))
    except:
        print('登录界面加载失败----')
    sendKeyElement_id(driver,'username',person.getAccount())
    sendKeyElement_id(driver,'xstr',person.getPassword())
    clickElement_link(driver,'立即登录')
def go2myproject(driver):
    x1 = """//span[@title="我的项目"]"""
    #driver.find_element(By.XPATH,x1).click()
    clickElement_xpath(driver,x1)
    x1 = """//span[@title="进行中的项目"]"""
    driver.find_element(By.XPATH,x1).click()
    # 添加项目
    x1="//button[@data-toggle='dropdown']"
    driver.find_element(By.XPATH,x1).click()

def baseInfo(driver,user):
    # 项目名称
    x1 = """//input[@class="form-control unNameBlanks required"]"""
    driver.find_element(By.XPATH,x1).send_keys("Test-"+user.getProjectType()+"-"+getTimeStrip())
    # 行业类别
    x1 = """//button[@data-id="industryCategory"]"""
    driver.find_element(By.XPATH,x1).click()
    driver.find_element(By.LINK_TEXT,"不限").click()
    # 项目分类
    x1 = """//button[@data-id="bidTypeSelect"]"""
    driver.find_element(By.XPATH,x1).click()
    driver.find_element(By.LINK_TEXT,"货物").click()
    x1 = """//button[@data-id="bidTypeSecondSelect"]"""
    driver.find_element(By.XPATH,x1).click()
    driver.find_element(By.LINK_TEXT,"材料").click()
    # 项目所属地区
    x1="""//button[@data-id="projectareaProvince"]"""
    driver.find_element(By.XPATH,x1).click()
    try:
        x1="""//li[@data-original-index="18"]"""
        driver.find_element(By.XPATH,x1).click()
    except:
        driver.find_element(By.LINK_TEXT,"北京市").click()
    # 需求部门
    x1 = """//input[@name="v(requireDepartName@String)"]"""
    driver.find_element(By.XPATH,x1).send_keys('需求部门')
    x1 = """//input[@name="v(requireLinkName@String)"]"""
    driver.find_element(By.XPATH,x1).send_keys(user.getName())
    x1 = """//input[@placeholder="请输入需求部门联系方式"]"""
    driver.find_element(By.XPATH,x1).send_keys(user.getPhone())
    if user.getDaili():
        dailiInfo(driver)


def dailiInfo(driver):
    x1 = """//span[@id="selectConsignContract"]"""
    driver.find_element(By.XPATH,x1).click()
    time.sleep(2)
    x1 = """//input[@placeholder="委托合同名称"]"""
    driver.find_element(By.XPATH,x1).send_keys("test")
    time.sleep(2)
    x1 = """//button[@id="modalDialogSearchBtn"]"""
    driver.find_element(By.XPATH,x1).click()
    time.sleep(3)
    x1 = """//input[@id="modalDialogId0"]"""
    driver.find_element(By.XPATH,x1).click()
    x1 = """//button[@id="modalDialogSelect"]"""
    driver.find_element(By.XPATH,x1).click()
    # 代理服务收取对象
    x1 = """//button[@data-id="serviceReceiveObject"]"""
    driver.find_element(By.XPATH,x1).click()
    try:
        driver.find_element(By.LINK_TEXT,"中标人").click()
    except:
        driver.find_element(By.LINK_TEXT,"成交人").click()
    try:
        x1 = """//button[@data-id="serviceFeeMode"]"""
        driver.find_element(By.XPATH,x1).click()
    except:
        x1 = """//button[@class="btn dropdown-toggle disabled btn-default"]"""
        driver.find_element(By.XPATH,x1).click()
    try:
        driver.find_element(By.LINK_TEXT,"固定金额").click()
    except:
        print("there is no need to click in 供应商入围")
    x1 = """//input[@name="exampelid3"]"""
    driver.find_element(By.XPATH,x1).click()
    time.sleep(2)
    x1 = """//td[@class="today active start-date active end-date available"]"""
    driver.find_element(By.XPATH,x1).click()
    #招标人
    x1 = """//span[@id="selectTenderee"]"""
    driver.find_element(By.XPATH,x1).click()
    time.sleep(2)
    try:
        x1 = """//input[@placeholder="招标人名称"]"""
        driver.find_element(By.XPATH,x1).send_keys("湖南大学")
    except:
        try:
            x1 = """//input[@name="Purchase.tendereeName"]"""
            driver.find_element(By.XPATH,x1).send_keys("湖南大学")
        except:
            x1 = """//input[@name="libTendereesCg.tendereeName"]"""
            driver.find_element(By.XPATH,x1).send_keys("湖南大学")
    x1 = """//button[@class="btn btn-primary btn-flat searchBtn"]/span"""
    driver.find_element(By.XPATH,x1).click()
    time.sleep(2)
    x1 = """//input[@id="modalDialogId0"]"""
    driver.find_element(By.XPATH,x1).click()
    x1  = """//button[@id="modalDialogSelect"]"""
    driver.find_element(By.XPATH,x1).click()
    try:
        time.sleep(2)
        x1 = """//button[@id="popup_cancel"]"""
        driver.find_element(By.XPATH,x1).click()
    except:
        print("There is no alert in this url")
def otherInfo(driver,user):
    amount = user.getAmount()
    # 备注
    x1 = """//div[@class="col-xs-24"]/textarea[@name="v(remark@String)"]"""
    driver.find_element(By.XPATH,x1).send_keys("备注:"+user.getName()+"---"+user.getProjectType())
    # 总投资
    x1 = """//input[@id="totalInvestment"]"""
    driver.find_element(By.XPATH,x1).send_keys(user.getAmount())
    # 采购项目预算金额
    x1 = """//input[@id="budgetAmount"]"""
    driver.find_element(By.XPATH,x1).send_keys(user.getAmount())
def InfoInput(driver,user):
    baseInfo(driver,user)
    otherInfo(driver,user)
def YiJia(driver,user):
    # 项目名称
    x1 = """//input[@class="form-control unNameBlanks required"]"""
    driver.find_element(By.XPATH,x1).send_keys("Test-"+user.getProjectType()+"-"+getTimeStrip())
    #采购方联系人
    x1 = """//span[@id="selectLinkName"]"""
    driver.find_element(By.XPATH,x1).click()
    time.sleep(2)
    # 联系人
    x1 = """//input[@name="feeBailTran.linkMan"]"""
    driver.find_element(By.XPATH,x1).send_keys(user.getName())
    x1 = """//button[@id="modalDialogSearchBtn"]"""
    driver.find_element(By.XPATH,x1).click()
    time.sleep(3)
    driver.find_element(By.ID,"modalDialogId0").click()
    x1 = """//button[@id="modalDialogSelect"]"""
    driver.find_element(By.XPATH,x1).click()
    driver.find_element(By.ID,"budgetAmount").send_keys(user.getAmount())
    driver.find_element(By.ID,"tenderQuoteDescription").send_keys("说明："+user.getProjectType()+"-"+getTimeStrip())


def CreateProjectByID(driver,user):
    id1 = user.getId()
    if(id1[0]=='1'):    
        # CA项目
        driver.find_element(By.LINK_TEXT,"网上开评标（需CA）").click()
        if(id1[1]=='1'):
            # 招标项目
            x1="//button[@class='btn btn-default zb']"
            driver.find_element(By.XPATH,x1).click()
            InfoInput(driver,user)
        elif(id1[1]=='2'):
            # 竞争性谈判
            x1 = """//button[@class="btn btn-default jzxtp"]"""
            driver.find_element(By.XPATH,x1).click()
            InfoInput(driver,user)
        elif(id1[1]=='3'):
            # 询价采购
            x1 = """//button[@class="btn btn-default xjcg"]"""
            driver.find_element(By.XPATH,x1).click()
            InfoInput(driver,user)
        elif(id1[1]=='4'):
            #竞争性磋商
            x1 = """//button[@class="btn btn-default jzxcs"]"""
            driver.find_element(By.XPATH,x1).click()
            InfoInput(driver,user)
        elif(id1[1]=='5'):
            #供应商入围
            x1 = """//div[@caandonline="10"]//button[@class="btn btn-default gysrw"]"""
            driver.find_element(By.XPATH,x1).click()
            InfoInput(driver,user)
    elif(id1[0]=='2'):
        # 网上开评标 无需CA
        driver.find_element(By.LINK_TEXT,"网上开评标（无需CA）").click()
        if(id1[1]=='1'):
            #单一来源采购项目
            x1 = """//button[@class="btn btn-default dylycg"]"""
            driver.find_element(By.XPATH,x1).click()
            InfoInput(driver,user)
        elif(id1[1]=='2'):
            #竞价项目
            x1 = """//button[@class="btn btn-default jj"]"""
            driver.find_element(By.XPATH,x1).click()
            InfoInput(driver,user)
        elif(id1[1]=='3'):
            #谈判采购
            x1 = """//button[@class="btn btn-default jzxtpxm3"]"""
            driver.find_element(By.XPATH,x1).click()
            InfoInput(driver,user)
        elif(id1[1]=='4'):
            #询价采购项目
            x1 = """//button[@class="btn btn-default xbjxm3"]"""
            driver.find_element(By.XPATH,x1).click()
            InfoInput(driver,user)
        elif(id1[1]=='5'):
            #供应商入围
            x1 = """//div[@caandonline="20"]//button[@class="btn btn-default gysrw"]"""
            driver.find_element(By.XPATH,x1).click()
            InfoInput(driver,user)
        elif(id1[1]=='6'):
            #议价项目
            if user.getDaili:
                x1 = """//button[@class="btn btn-default yj"]"""
                driver.find_element(By.XPATH,x1).click()
                YiJia(driver,user)
            else:
                pi.alert("Wrong thing in this project")
if __name__=="__main__":
    """
    0 xz18073180118 1 田甜 2 local 3 12 4 120 5 61.187.51.25:8084
    """
    settings = GetSetting()
    for i in settings:
        print(i) 
    user = User(settings[0],settings[1],settings[4],GetFullUrl(settings),GetProjectType(settings),settings[3])
    options = webdriver.ChromeOptions()
    options.add_argument("--start-maximized")
    driver = webdriver.Chrome(options=options)
    pmlogin(driver,user)
    go2myproject(driver)
    CreateProjectByID(driver,user)
